using Microsoft.Extensions.DependencyInjection;

using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.AutoMapper;
using Volo.Abp.Modularity;

namespace WL.Think.Abp.Extensions;

public static class ServiceConfigurationContextExtension
{
    /// <summary>
    /// 预配置应用程序的构建块
    /// </summary>
    /// <param name="context"></param>
    /// <param name="enable"></param>
    /// <returns></returns>
    public static ServiceConfigurationContext ConfigureApplicationPart<TModule>(this ServiceConfigurationContext context, Action<IMvcBuilder>? builder = null)
    {
        context.Services.PreConfigure<IMvcBuilder>(b =>
        {
            b.AddApplicationPartIfNotExists(typeof(TModule).Assembly);
            builder?.Invoke(b);
        });
        return context;
    }

    /// <summary>
    /// 配置自动API控制器
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static ServiceConfigurationContext ConfigureAutoApiControllers<TModule>(this ServiceConfigurationContext context, Action<AbpAspNetCoreMvcOptions>? action = null)
    {
        context.Services.Configure<AbpAspNetCoreMvcOptions>(opts =>
        {
            opts.ConventionalControllers.Create(typeof(TModule).Assembly);
            action?.Invoke(opts);
        });
        return context;
    }


    /// <summary>
    /// 配置AutoMapper
    /// </summary>
    /// <param name="context"></param>
    /// <param name="enable"></param>
    /// <returns></returns>
    public static ServiceConfigurationContext ConfigureAutoMapper<TModule>(this ServiceConfigurationContext context, Action<AbpAutoMapperOptions>? action = null) where TModule : AbpModule
    {
        context.Services.Configure<AbpAutoMapperOptions>(opts =>
        {
            opts.AddCollectionMappers();
            opts.AddMaps<TModule>();
            action?.Invoke(opts);
        });
        return context;
    }
}
